package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.advanced;

import io.netty.channel.Channel;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.NettyHttpClientProxyClient;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.socket.NettyHttpClientProxyClientProxySocket;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.HandleChannelTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.http.AbstractHttpClientProxyClientTypeAdvanced;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;
import org.wu.framework.spring.utils.SpringContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * http 远程代理
 * 客户端：客户端远程到服务端、客户端远程到客户端
 *
 */
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ClientHandleHttpClientProxyClientTypeAdvanced extends
        AbstractHttpClientProxyClientTypeAdvanced<NettyProxyMsg> {


    /**
     * 处理当前数据
     *
     * @param nettyChannelContext       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
        Channel channel = nettyChannelContext.channel();
        String targetPortString = nettyProxyMsg.targetPort();
        String targetIpString = nettyProxyMsg.targetIp();
        byte[] data = nettyProxyMsg.getData();
        byte[] clientId = nettyProxyMsg.getClientId();
        List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList = new ArrayList<>(SpringContextHolder.getApplicationContext().getBeansOfType(HandleChannelTypeAdvanced.class).values());
        NettyClientProperties nettyClientProperties = SpringContextHolder.getBean(NettyClientProperties.class);
        // 判断代理到客户端还是服务端
        NettyHttpClientProxyClient nettyHttpClientProxyClient = new NettyHttpClientProxyClient();
        nettyHttpClientProxyClient.setSsl(false);
        nettyHttpClientProxyClient.setTargetIp(targetIpString);
        nettyHttpClientProxyClient.setTargetPort(Integer.parseInt(targetPortString));
        nettyHttpClientProxyClient.setTargetClientId(new String(clientId));

        nettyHttpClientProxyClient.setHandleChannelTypeAdvancedList(handleChannelTypeAdvancedList);
        nettyHttpClientProxyClient.setNettyClientProperties(nettyClientProperties);
        nettyHttpClientProxyClient.setData(data);

        NettyHttpClientProxyClientProxySocket.buildTransferServer(nettyHttpClientProxyClient, channel);
    }
}
